package com.xjcs.saplingplan.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.xjcs.saplingplan.databinding.ItemCountdownCatePopBinding
import com.xjcs.saplingplan.room.bean.countdown.PlanCateBean

class CountdownCatePopAdapter(
    private val context: Context,
    private val data: MutableList<PlanCateBean>,
    private var curCateName: String
) : RecyclerView.Adapter<CountdownCatePopAdapter.ItemCountdownCateViewHolder>() {

    //当前选中的位置 -1表示未选中
    private var selectedPosition: Int = -1

    init {
        kotlin@ run {
            data.forEachIndexed { index, bean ->
                if (bean.planCateName == curCateName) {
                    selectedPosition = index
                    return@run
                }
            }
        }
    }

    fun getSelectedCateName(): String {
        return if (selectedPosition != -1) data[selectedPosition].planCateName else ""
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemCountdownCateViewHolder {
        val binding = ItemCountdownCatePopBinding.inflate(LayoutInflater.from(context), parent, false)
        return ItemCountdownCateViewHolder(binding) { pos -> onItemClick(pos) }
    }

    private fun onItemClick(position: Int) {
        val oldPosition = selectedPosition
        selectedPosition = position
        notifyItemChanged(oldPosition)
        notifyItemChanged(selectedPosition)
    }

    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: ItemCountdownCateViewHolder, position: Int) {
        val item = data.getOrNull(position)
        holder.bind(item)
    }

    class ItemCountdownCateViewHolder(
        binding: ItemCountdownCatePopBinding,
        private val onItemClick: (Int) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: PlanCateBean?) {
        }
    }
}